const app = getApp();

export function openWebsocket() {
  wx.onSocketOpen(resp => {
    console.log('websocket打开成功', resp);
    app.globalData.websocketConnected = true;
  });

  wx.onSocketError(err => {
    console.log('websocket错误', err);
    closeWebsocket();
  });

  wx.onSocketClose(resp => {
    console.log('websocket关闭', resp);
    app.globalData.websocketConnected = false;
  });

  wx.onSocketMessage(data => {
    EventBusInstance.emit('chat', JSON.parse(data.data));
  });


  const token = app.globalData.token;
  console.log(token);
  const socketClient = wx.connectSocket({
    url: `${baseWebsocketUrl}/websocket/endpoint/${app.globalData.currentUserInfo.id}`,
    header: {
      'X-Auth-Token': token
    },
  });
  app.globalData.socketClient = socketClient;
}

function closeWebsocket() {
  wx.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！')
  })
}

